const mysql = require('mysql')

const dbConf = {
    host: 'localhost',
    user: 'root',
    password: 'guzhan321',
    database: 'node_test'
}

// 建立连接

const conn = mysql.createConnection(dbConf)

const createTable = `
create table if not exists test_order(
	id int not null auto_increment,
	message varchar(255) null,
	price double null,
	primary key(id)
);`

// 插入数据
const insertData = `insert into test_order set ?;`
// 查询数据
const select = `select * from test_order;`
// 删除一行
let del = `delete from ?? where ?? = ?`
let update = `UPDATE ?? SET ? where ?? = ?`


const asyncQuery = (sql, params) => {
    return new Promise((resolve, reject) => {
        conn.query(sql, params, (err, ...args) => {
            if (err) {
                reject(err)
            } else {
                resolve(args)
            }
        })
    })
}

/*
conn.connect(err => {
    if (err) {
        throw err
    }
    console.log('1. 连接成功');

    conn.query(createTable, (err) => {
        if (!err) {
            console.log('2. 表创建成功');
            // 插入数据
            conn.query(insertData, {
                message: 'Mac',
                price: 12999,
            }, (err, data) => {
                if (!err) {
                    console.log('3. 插入成功');
                }
            })
            // 查询数据
            // 删除
            // 修改
        }
    })
})
*/

conn.connect(async (err) => {    
    if (err) {
        throw err
    }
    console.log('1. 连接成功');
    
    console.log('2. 表创建成功');
    await asyncQuery(createTable)

    // 插入数据
    let data = await asyncQuery(
        insertData, {
            message: 'Mac',
            price: Math.round(Math.random() * 99999),
    })
    // 删除
    // ?? where ?? = ?`
    // await asyncQuery(del, ['test_order', 'price', 9052])
    // 修改

    // await asyncQuery(update, ['test_order', { price: 1 }])

    // 95880
    await asyncQuery(update, ['test_order', { price: 12999 }, 'price', 95880])
    
    // 查询数据
    data = await asyncQuery(select)
    console.log('查询数据: ',data);
})
